import FileSaver from "file-saver";
import JSZip from "jszip";
import axios from "axios";
// 单个二维码导出
export const singleExportQRCode = (url, name) => {
  // console.log(url)
  // console.log(name)
  if (!name) {
    FileSaver.saveAs(url); // 未传入导出图片名称
  } else {
    FileSaver.saveAs(url, `${name}.jpg`); // 通过fileSaver导出下载图片
  }
};

// 下载二维码图片并压缩
function getImgArrayBuffer(url) {
  return new Promise((resolve, reject) => {
    axios({
      method: "get",
      url,
      responseType: "blob",
    })
      .then((response) => {
        resolve(response.data);
      })
      .catch((error) => {
        reject(error.toString());
      });
  });
}
// 批量二维码导出
export const batchExportQRCode = (list, zipNmae) => {
  let zip = new JSZip();
  var imgObj = {};
  let promises = [];
  for (let obj of list) {
    const promise = getImgArrayBuffer(obj.qr_code).then((data) => {
      zip.file(obj.title + ".png", data, { binary: true }); // 逐个添加文件
      imgObj[obj.title] = data;
    });
    promises.push(promise);
  }
  // console.log(promises)
  Promise.all(promises).then(async () => {
    try {
      const content = await zip.generateAsync({ type: "blob" });
      await FileSaver.saveAs(content, zipNmae);
      // const newDate = +new Date()
      // console.log('new-',newDate)
    } catch (error) {
      console.log(error);
    }
  });
};
